package com.example.ajouconqueror;

import java.io.IOException;
import java.io.UnsupportedEncodingException;
import java.util.ArrayList;
import java.util.List;

import org.apache.http.HttpEntity;
import org.apache.http.HttpHost;
import org.apache.http.HttpResponse;
import org.apache.http.NameValuePair;
import org.apache.http.client.ClientProtocolException;
import org.apache.http.client.HttpClient;
import org.apache.http.client.entity.UrlEncodedFormEntity;
import org.apache.http.client.methods.HttpPost;
import org.apache.http.impl.client.DefaultHttpClient;
import org.apache.http.message.BasicNameValuePair;
import org.apache.http.util.EntityUtils;

import android.app.Activity;
import android.app.ProgressDialog;
import android.content.Intent;
import android.os.AsyncTask;
import android.os.Bundle;
import android.util.Log;
import android.view.Menu;
import android.view.View;
import android.view.View.OnClickListener;
import android.widget.Button;
import android.widget.EditText;
import android.widget.Toast;

import com.example.classes.IP;
import com.example.classes.UserApplication;

public class MainLogin extends Activity implements OnClickListener {
	//main activity. In this activity you can login...
	
	
	//variables for this activity
	private EditText ID, Pass;
	private Button LoginGO, accountbuttonGO;
	IP ip = new IP();
	private final String HOST = ip.ip;
	private final int PORT = 8080;

	private final String PATH_POST = "/AjouConquerorServer-war/webresources/ajouconquerorbeans.login/Logincheck";
	ProgressDialog dialog;
	
	private String path;
	String uid;
	UserApplication UserApp;

	// Our RESTful web service supports JSON and XML, but this
	// client supports only JSON.

	private String MIME = "text/plain";

	@Override
	protected void onCreate(Bundle savedInstanceState) {
		super.onCreate(savedInstanceState);
		setContentView(R.layout.activity_main_login);
		UserApp = (UserApplication) getApplication();
		UserApp.reset();

		ID = (EditText) findViewById(R.id.IDeditText);
		Pass = (EditText) findViewById(R.id.PasseditText);

		LoginGO = (Button) findViewById(R.id.Loginbutton);
		LoginGO.setOnClickListener(this);

		accountbuttonGO = (Button) findViewById(R.id.accountbutton);
		accountbuttonGO.setOnClickListener(this);
	}

	@Override
	public boolean onCreateOptionsMenu(Menu menu) {
		// Inflate the menu; this adds items to the action bar if it is present.
		getMenuInflater().inflate(R.menu.main_login, menu);
		return true;
	}

	@Override
	public void onClick(View v) {

		if (v.equals(LoginGO)) {
			//If you click the Login button you can login
			path = PATH_POST;
			AsyncCreate t = new AsyncCreate();
			t.execute();
		} else if (v.equals(accountbuttonGO)) {
			//If you click the account button you can change activity for making accounts.
			Intent i = new Intent(MainLogin.this, account.class);
			startActivity(i);
		}

	}

	private class AsyncCreate extends AsyncTask<String, Void, String> {

		@Override
		protected void onPreExecute() {
			// When you are doing Login, the dialog is showed
			dialog = ProgressDialog.show(MainLogin.this,"","Now Logining",true);
		}

		@Override
		protected String doInBackground(String... params) {

			String result = "false";
			// user id and pass word input setting
			// create() method of the web service needs a Person object as input
			uid = ID.getText().toString();
			String id = uid;
			String upass = Pass.getText().toString();
			String pas = upass;
			//setting for post PORT is 8080 and HOST is server's ip and path is the function's path.
			HttpHost target = new HttpHost(HOST, PORT);
			HttpClient client = new DefaultHttpClient();
			HttpPost post = new HttpPost(path);
			//content type is application/x-www-form-urlencoded because this AsyncTask send 2 values to server.
			// set the MIME type for POST message body.
			post.setHeader("Content-Type", "application/x-www-form-urlencoded");

			HttpEntity entity = null;

			List<NameValuePair> idpair = new ArrayList<NameValuePair>();
			idpair.add(new BasicNameValuePair("uid", id));
			idpair.add(new BasicNameValuePair("pass", pas));

			try {
				//After setting,it is executed
				post.setEntity(new UrlEncodedFormEntity(idpair));

				HttpResponse response = client.execute(target, post);

				// Status code 204 is success with "No content".
				// This happens when a RESTful method returns void.
				if (response.getStatusLine().getStatusCode() < 400) {
					//If you have an error with client and server communication the result is get.
					result = "get";
				} 
				// You can get a result String. success or fail
				entity = response.getEntity();

				String str = EntityUtils.toString(entity);

				// convert JSON to Person
				result = str;

				Log.i("errorr:", "s "
						+ response.getStatusLine().getStatusCode());
			} catch (UnsupportedEncodingException e) {
				e.printStackTrace();
				Log.i("errorr:", "UnsupportedEncodingException");
			} catch (ClientProtocolException e) {
				e.printStackTrace();
				Log.i("errorr:", "ClientProtocolException");
			} catch (IOException e) {
				e.printStackTrace();
				Log.i("errorr:", "IOException");
			}
			return result;
		}

		@Override
		protected void onPostExecute(String result) {
			//when you get a result the dialog is ended.
			dialog.dismiss();
			
			if (result.equals("success")) {
				//When you get"success" from the server you can start gameroomactivity.
				Intent i = new Intent(MainLogin.this, GameRoomActivity.class);
				startActivity(i);
				UserApp.setUserid(uid);
				Toast.makeText(MainLogin.this, "Login success", Toast.LENGTH_SHORT)
						.show();
			} else if (result.equals("fail")) {
				//When you get "fail" from the server you can see the toast massage.
				Toast.makeText(MainLogin.this, "Check your ID and password",
						Toast.LENGTH_SHORT).show();
			} else {
				//else there are error, you can see the toast message "error"
				Toast.makeText(MainLogin.this, "error", Toast.LENGTH_SHORT).show();
			}

		}
	}

}
